<template>
  <!-- 变更管理 -->
  <div class="table-box" v-loading="loading">
    <div style="width: 100%">
      <div
        style="
          display: flex;
          justify-content: space-between;
          padding: 10px;
          margin-bottom: 10px;
          background: #ffffff;
          border-radius: 5px;
        "
      >
        <div class="filter-box" @click="getChangeByType('countAllChanges')">
          <div class="num">{{ countAllChanges }}</div>
          <div class="text">变更总数</div>
        </div>
        <div class="filter-box" @click="getChangeByType('82')">
          <div class="num">{{ countNewChanges }}</div>
          <div class="text">新建变更</div>
        </div>
        <div class="filter-box" @click="getChangeByType('80')">
          <div class="num">{{ countReChanges }}</div>
          <div class="text">变更复审</div>
        </div>
        <div class="filter-box" @click="getChangeByType('81')">
          <div class="num">{{ countDoneChanges }}</div>
          <div class="text">变更完成</div>
        </div>
        <!-- <div class="filter-box" @click="getChangeByType(item.id)" v-for="item in countChangeList" :key="item.id">
          <div class="num">{{ item.data }}</div>
          <div class="text">{{ item.label }}</div>
        </div> -->
      </div>
    </div>
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback" row-key="eno">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="'add'" plain @click="addChange">变更新增</el-button>
        <!-- <el-button type="primary" :disabled="!scope.isSelected" plain>编辑</el-button> -->
        <el-button type="danger" v-auth="'delete'" :disabled="!scope.isSelected" plain @click="delSelectItem(scope.selectedList)">
          删除
        </el-button>
        <el-button type="primary" plain @click="searchVisible = true">搜索</el-button>
      </template>
      <!-- 优先级 -->
      <template #priorityName="scope">
        <div v-if="scope.row.priorityColor" :style="{ background: scope.row.priorityColor }" style="color: #ffffff">
          {{ scope.row.priorityName }}
        </div>
        <div v-else>{{ scope.row.priorityName }}</div>
      </template>
      <!-- 影响范围 -->
      <template #effectRangeName="scope">
        <div v-if="scope.row.effectRangeColor" :style="{ background: scope.row.effectRangeColor }" style="color: #ffffff">
          {{ scope.row.effectRangeName }}
        </div>
        <div v-else>{{ scope.row.effectRangeName }}</div>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link v-auth="'view'" :icon="View" @click="openDetails(scope.row)">查看</el-button>
        <el-button type="primary" link v-auth="'edit'" :icon="EditPen" @click="editChange(scope.row)">编辑</el-button>
        <el-button type="primary" link v-auth="'delete'" :icon="Delete" @click="deleteItem(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <!-- 搜索 -->
    <el-dialog v-model="searchVisible" title="搜索" width="920">
      <el-form label-width="72">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="所属客户">
              <el-select v-model="filterForm.companyNo" clearable>
                <el-option v-for="(item, index) in orgList" :key="index" :label="item.orgName" :value="item.orgNo"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题">
              <el-input v-model="filterForm.etitle" placeholder="请输入标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类">
              <!-- <el-select v-model="filterForm.categoryNo" clearable>
                <el-option v-for="(item, index) in cateList" :key="index" :label="item.cname" :value="item.id"></el-option>
              </el-select> -->
              <el-tree-select
                v-model="filterForm.categoryNo"
                lazy
                :load="cateTreeLoad"
                :cache-data="cacheCateData"
                check-strictly
                :render-after-expand="false"
                placeholder="请选择变更分类"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编号">
              <el-input v-model="filterForm.changeNo" placeholder="请输入编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="filterForm.statusNo" clearable>
                <el-option v-for="(item, index) in statusList" :key="index" :label="item.dname" :value="item.dcode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="filterForm.priorityNo" clearable>
                <el-option v-for="(item, index) in priorityList" :key="index" :label="item.dname" :value="item.dcode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="影响">
              <el-select v-model="filterForm.effectRangeNo" clearable>
                <el-option
                  v-for="(item, index) in effectRangeList"
                  :key="index"
                  :label="item.dname"
                  :value="item.dcode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急度">
              <el-select v-model="filterForm.seriousnessNo" clearable>
                <el-option
                  v-for="(item, index) in seriousnessList"
                  :key="index"
                  :label="item.dname"
                  :value="item.dcode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="filterTime"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人">
              <div style="display: flex; width: 100%">
                <el-input
                  style="flex: 1; overflow: hidden"
                  v-model="filterForm.createdByFullName"
                  placeholder="请输入申请人名称"
                ></el-input>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  :icon="Search"
                  @click="selectUser('createdByFullName')"
                ></el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指派组">
              <el-cascader
                v-model="assigneeGroupNo"
                :options="groupList"
                :show-all-levels="false"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术员">
              <div style="display: flex; width: 100%">
                <el-input
                  style="flex: 1; overflow: hidden"
                  v-model="filterForm.assigneeFullName"
                  placeholder="请输入技术员名称"
                ></el-input>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  :icon="Search"
                  @click="selectUser('assigneeFullName')"
                ></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="clearSearchData">重置</el-button>
          <el-button type="primary" @click="search">搜索</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <DetailsMask ref="detailsMask" @change="refreshList(false)"></DetailsMask>
    <!-- 选择用户弹窗 -->
    <SelectUserMask ref="selectUserMask" @change="selectUserChange"></SelectUserMask>
    <!-- 新增、编辑 -->
    <AddChangeMask ref="addChangeMask" @add="refreshList(true)" @change="refreshList(false)"></AddChangeMask>
  </div>
</template>

<script setup lang="ts" name="changeManagement">
import { ref, reactive, computed, onMounted, watch } from "vue";
// import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, EditPen, View, Search } from "@element-plus/icons-vue";

import { countChange, findPagerChange, deleteChange, getCategoryTree } from "@/api/modules/changeManagement";

import { useUserStore } from "@/stores/modules/user";
import { useAllChangeOptions } from "@/stores/modules/change";

import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { User } from "@/api/interface";
import SelectUserMask from "@/components/SelectUserMask/index.vue";
import DetailsMask from "@/components/Change/DetailsMask.vue";
import AddChangeMask from "@/components/Change/AddChangeMask.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
const { BUTTONS } = useAuthButtons();
const userStore = useUserStore();
const allChangeOptions = useAllChangeOptions();
// const router = useRouter();

// 变更统计
const countAllChanges = ref<any>();
const countNewChanges = ref("");
const countReChanges = ref("");
const countDoneChanges = ref("");
const countChangeList = ref<any[]>([]);
const getCountChange = async () => {
  const params = {
    "queryDTO.lastUpdater": userStore.username,
    "queryDTO.creator": userStore.username,
    "queryDTO.groupField": "status",
    "queryDTO.countQuery": "countAllChanges"
  };
  const res = (await countChange(params)) as any;
  countChangeList.value = res;
  console.log(res);
  res.forEach((item: any) => {
    if (item.label === "变更复审") {
      countReChanges.value = item.data;
    }
    if (item.label === "新建变更") {
      countNewChanges.value = item.data;
    }
    if (item.label === "变更完成") {
      countDoneChanges.value = item.data;
    }
  });
  countAllChanges.value = res[0].total;
};
const changeType = ref("");
const isType = ref(false);
const getChangeByType = async (type: any) => {
  changeType.value = type;
  isType.value = true;
  refreshList(true);
};
interface OrgItem {
  orgNo: string;
  orgName: string;
}

// 所属客户列表
const orgList = computed(() => {
  let list = ref<OrgItem[]>(allChangeOptions.orgList || []);
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.value.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.value.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list.value;
});

interface CateItem {
  id: string;
  cname: string;
}

// 分类列表
const cateList = computed<any[]>(() => {
  let list = JSON.parse(JSON.stringify(allChangeOptions.cateList));
  list.forEach((item: any) => {
    item.label = item.cname;
    item.value = item.id;
    if (item.children && item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.cname;
        vo.value = vo.id;
      });
    }
  });
  return list;
});

const cacheCateData = ref<any[]>([]);

// 查询分类树
const cateTreeLoad = (node, resolve) => {
  if (node.level == 0) {
    resolve(cateList.value);
  } else {
    // 获取分类列表
    getCategoryTree({
      types: "Change",
      parentEventId: node.data.value
    }).then((res: any) => {
      res.forEach(item => {
        item.label = item.attr.cname;
        item.value = item.attr.id;
      });
      resolve(res);
    });
  }
};

interface UniversalItem {
  dcode: string;
  dname: string;
}

// 变更状态
const statusList = computed<UniversalItem[]>(() => {
  return allChangeOptions.statusList;
});

// 优先级列表
const priorityList = computed<UniversalItem[]>(() => {
  return allChangeOptions.priorityList;
});

// 影响列表
const effectRangeList = computed<UniversalItem[]>(() => {
  return allChangeOptions.effectRangeList;
});

// 紧急度列表
const seriousnessList = computed<UniversalItem[]>(() => {
  return allChangeOptions.seriousnessList;
});

// 指派组
const groupList = computed(() => {
  let list = JSON.parse(JSON.stringify(allChangeOptions.groupList));
  list.forEach(item => {
    item.label = item.orgName;
    item.value = item.orgNo;
    if (item.children) {
      item.children.forEach(vo => {
        vo.label = vo.orgName;
        vo.value = vo.orgNo;
        if (vo.children) {
          vo.children.forEach(v => {
            v.label = v.orgName;
            v.value = v.orgNo;
          });
        }
      });
    }
  });
  return list;
});

onMounted(() => {
  getCountChange();
  if (
    orgList.value.length == 0 ||
    priorityList.value.length == 0 ||
    priorityList.value.length == 0 ||
    seriousnessList.value.length == 0 ||
    effectRangeList.value.length == 0 ||
    statusList.value.length == 0
  ) {
    allChangeOptions.getAllOptions();
  }
});

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "eno", label: "ID", fixed: "left", width: 80 },
  { prop: "companyName", label: "所属客户", width: 160 },
  { prop: "changeNo", label: "编号", width: 200 },
  { prop: "etitle", label: "标题", width: 160 },
  { prop: "categoryName", label: "分类", width: 100 },
  { prop: "statusName", label: "状态", width: 110 },
  { prop: "closeCode", label: "关闭代码", width: 140 },
  { prop: "orgName", label: "指派组", width: 180 },
  { prop: "technicianName", label: "技术员", width: 100 },
  { prop: "priorityName", label: "优先级", width: 80 },
  { prop: "effectRangeName", label: "影响范围", width: 100 },
  { prop: "createTime", label: "创建时间", width: 170 },
  { prop: "creator", label: "创建者", width: 100 },
  { prop: "operation", label: "操作", fixed: "right", width: 240 }
]);

const filterForm = reactive({
  companyNo: "", // 所属客户
  etitle: "", // 标题
  changeNo: "", // 编号
  categoryNo: "", // 分类
  priorityNo: "", // 优先级
  effectRangeNo: "", // 影响
  seriousnessNo: "", // 紧急度
  statusNo: "", // 状态
  startTime: "", // 开始时间
  entTime: "", // 结束时间
  createdByFullName: "", // 申请人
  assigneeGroupNo: "", // 指派组
  assigneeFullName: "" // 技术员
});

const assigneeGroupNo = ref([]);

watch(
  () => assigneeGroupNo.value,
  val => {
    if (val.length == 3) {
      filterForm.assigneeGroupNo = val[2];
    } else {
      filterForm.assigneeGroupNo = "";
    }
  }
);

const form = reactive({
  companyNo: "", // 所属客户
  etitle: "", // 标题
  changeNo: "", // 编号
  categoryNo: "", // 分类
  priorityNo: "", // 优先级
  effectRangeNo: "", // 影响
  seriousnessNo: "", // 紧急度
  statusNo: "", // 状态
  startTime: "", // 开始时间
  entTime: "", // 结束时间
  createdByFullName: "", // 申请人
  assigneeGroupNo: "", // 指派组
  assigneeFullName: "" // 技术员
});

const filterTime = ref<any>([]);

watch(
  () => filterTime.value,
  val => {
    filterForm.startTime = val[0];
    filterForm.entTime = val[1];
  }
);

// ProTable 实例
const proTable = ref<ProTableInstance>();
const loading = ref(false);
const isRefresh = ref(false);

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
const getTableList = (params: any) => {
  loading.value = true;
  let page = params.pageNum;
  if (isRefresh.value) {
    page = 1;
    isRefresh.value = false;
  }
  if (isType.value) {
    if (changeType.value === "countAllChanges") {
      return findPagerChange({
        "queryDTO.lastUpdater": userStore.username,
        "queryDTO.companyNo": form.companyNo,
        "queryDTO.etitle": form.etitle,
        "queryDTO.changeNo": form.changeNo,
        "queryDTO.categoryNo": form.categoryNo,
        "queryDTO.priorityNo": form.priorityNo,
        "queryDTO.effectRangeNo": form.effectRangeNo,
        "queryDTO.seriousnessNo": form.seriousnessNo,
        "queryDTO.statusNo": form.statusNo,
        "queryDTO.startTime": form.startTime,
        "queryDTO.entTime": form.entTime,
        "queryDTO.createdByFullName": form.createdByFullName,
        "queryDTO.assigneeGroupNo": form.assigneeGroupNo,
        "queryDTO.assigneeFullName": form.assigneeFullName,
        _search: false,
        sidx: "eno",
        sord: "desc",
        page: page,
        rows: params.pageSize
      }).catch(() => {
        loading.value = false;
      });
    } else {
      const statusParams = {
        "queryDTO.lastUpdater": userStore.username,
        "queryDTO.statusNo": changeType.value,
        _search: false,
        sidx: "eno",
        sord: "desc",
        page: page,
        rows: params.pageSize
      };
      return findPagerChange(statusParams).catch(() => {
        loading.value = false;
      });
    }
  } else {
    return findPagerChange({
      "queryDTO.lastUpdater": userStore.username,
      "queryDTO.companyNo": form.companyNo,
      "queryDTO.etitle": form.etitle,
      "queryDTO.changeNo": form.changeNo,
      "queryDTO.categoryNo": form.categoryNo,
      "queryDTO.priorityNo": form.priorityNo,
      "queryDTO.effectRangeNo": form.effectRangeNo,
      "queryDTO.seriousnessNo": form.seriousnessNo,
      "queryDTO.statusNo": form.statusNo,
      "queryDTO.startTime": form.startTime,
      "queryDTO.entTime": form.entTime,
      "queryDTO.createdByFullName": form.createdByFullName,
      "queryDTO.assigneeGroupNo": form.assigneeGroupNo,
      "queryDTO.assigneeFullName": form.assigneeFullName,
      _search: false,
      sidx: "eno",
      sord: "desc",
      page: page,
      rows: params.pageSize
    }).catch(() => {
      loading.value = false;
    });
  }
};

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  loading.value = false;
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const searchVisible = ref(false);

// 打开选择用户弹窗
const selectUserMask = ref();
const selectUserType = ref("");
const selectUser = (type: string) => {
  selectUserType.value = type;
  selectUserMask.value.open();
};

// 选择用户
const selectUserChange = user => {
  filterForm[selectUserType.value] = user.fullName;
};

const refreshList = refresh => {
  isRefresh.value = refresh;
  proTable.value?.getTableList();
};

const search = () => {
  form.companyNo = filterForm.companyNo;
  form.etitle = filterForm.etitle;
  form.changeNo = filterForm.changeNo;
  form.categoryNo = filterForm.categoryNo;
  form.priorityNo = filterForm.priorityNo;
  form.effectRangeNo = filterForm.effectRangeNo;
  form.seriousnessNo = filterForm.seriousnessNo;
  form.statusNo = filterForm.statusNo;
  form.startTime = filterForm.startTime;
  form.entTime = filterForm.entTime;
  form.createdByFullName = filterForm.createdByFullName;
  form.assigneeGroupNo = filterForm.assigneeGroupNo;
  form.assigneeFullName = filterForm.assigneeFullName;

  searchVisible.value = false;
  refreshList(true);
};

// 重置搜索
const clearSearchData = () => {
  filterForm.companyNo = "";
  filterForm.etitle = "";
  filterForm.changeNo = "";
  filterForm.categoryNo = "";
  filterForm.priorityNo = "";
  filterForm.effectRangeNo = "";
  filterForm.seriousnessNo = "";
  filterForm.statusNo = "";
  filterForm.startTime = "";
  filterForm.entTime = "";
  filterForm.createdByFullName = "";
  filterForm.assigneeGroupNo = "";
  filterForm.assigneeFullName = "";

  filterTime.value = [];
  assigneeGroupNo.value = [];
};

// 新增
const addChangeMask = ref();
const addChange = () => {
  addChangeMask.value.open();
};

// 编辑
const editChange = item => {
  addChangeMask.value.open(item);
};

// 批量删除
const delSelectItem = list => {
  let ids = list.map(item => {
    return item.eno;
  });
  ElMessageBox.confirm("确定要删除选中项？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      deleteChange({
        ids: ids.join(",")
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("删除成功");
          proTable.value?.clearSelection();
          refreshList(true);
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // cancel operation
    });
};

// 删除
const deleteItem = item => {
  ElMessageBox.confirm("确定要删除该变更？", "提示")
    .then(() => {
      loading.value = true;
      deleteChange({
        ids: item.eno
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("删除成功");
          // 刷新列表
          refreshList(true);
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 点击取消
    });
};

// 查看详情
const detailsMask = ref();
const openDetails = item => {
  detailsMask.value.open(item);
};
</script>

<style lang="scss" scoped>
.details-box {
  overflow: hidden;
  table {
    width: 100%;
    border-collapse: collapse;
  }
  table,
  th,
  td {
    border: 1px solid #e5e5e5;
  }
  th {
    width: 120px;
    padding: 5px;
  }
  td {
    padding: 5px;
  }
}
.filter-box {
  box-sizing: border-box;
  width: 24%;
  padding: 15px 0 18px;
  margin-top: 10px;
  text-align: center;
  cursor: pointer;
  background-color: var(--el-menu-active-bg-color);
  background-size: 100% 100%;
  border-radius: 10px;
  transition: all 0.3s;
  .num {
    font-size: 20px;
    font-weight: bold;
    color: var(--el-color-primary);
  }
  .text {
    margin-top: 5px;
    font-size: 14px;
  }
}
</style>
